﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CdcSoftware.Pivotal.Applications.Core.Client;
using CdcSoftware.Pivotal.Applications.Core.Common;
using CdcSoftware.Pivotal.Engine;
using CdcSoftware.Pivotal.Engine.Client.Services.Interfaces;
using CdcSoftware.Pivotal.Engine.UI.Forms;
using CdcSoftware.Pivotal.Engine.UI.DataTypes.Navigation;

namespace Pcm.Inventory.Client.FormTasks
{
    public partial class RE_Inventory_Transfer : FormClientTask
    {
        /// <summary>
        /// The Form Client Task class to undertake some specfic tasks for one business object associated to a specified form.
        /// It will call Form Server Task.
        /// </summary>
        /// <history>
        /// Revision       Date           Author        Description
        /// 6.0.9.0        14/12/2011     VT            Initial Version
        /// </history>

        #region Constants

        public struct Status
        {
            public const string FieldName = "Status";
            public const string Issued = "Issued";
            public const string Cancel = "Cancel";
            public const string New = "New";
            public const string Hold = "Hold";
            public const string Pending = "Pending";
            public const string Received = "Received";
        }

        const string PrintGoodsIssueButton = "btnPrintGoods";
        const string CreateNewGIButton = "btnCreateNewGI";
        const string RemoveItemsButton = "btnRemoveItems";
        const string CreateCopyButton = "btnCreateCopy";

        const string CashierLoginsForTodaywithStoreQueryName = "RE_All Cashier Logins for Today where EndTime is Null with Store ?";
        const string CashierLoginsForTodaywithPOSQueryName = "RE_All Cashier Logins for Today where EndTime is Null with POS ?";
        const string EmployeeTableName = "Employee";
        const string REStorePOSIdFieldName = "RE_Store_POS_Id";
        const string StaffIdFieldName = "Staff_Id";
        const string FromStaffIdFieldName = "From_Staff_Id";
        const string ToStaffIdFieldName = "To_Staff_Id";
        const string ProductIdFieldName = "Product_Id";
        const string REProductSKUwithBarcodeQueryName = "RE Product SKU Barcode is ?";
        const string ProductBarcodeFieldName = "Product_Barcode";
        const string REProductSKUIdFieldName = "RE_Product_SKU_Id";
        const string MarkedAsDeleteFieldName = "Marked_As_Delete";
        const string InventoryForSKUAndStorageLocationQueryName = "RE_Inventory for SKU? Storage Location?";
        const string ProductSKUswithProductSKUIdQueryName = "RE Product SKUs with Product SKU Id?";
        const string FromStorageLocationIdFieldName = "From_Storage_Location_Id";
        const string ToStorageLocationIdFieldName = "To_Storage_Location_Id";
        const string BarCodeFieldName = "Barcode";

        const string ColorFieldName = "Color";
        const string SizeFieldName = "Size";
        const string QuantityIssuedFieldName = "Quantity_Issued";
        const string QuantityReceivedFieldName = "Quantity_Received";
        const string QuantityOpenFieldName = "Quantity_Open";
        const string ReceivedFieldName = "Received";
        const string GIExternalSystemUpdatedFieldName = "GI_External_System_Updated";
        const string IssueDateFieldName = "Issue_Date";
        const string ReceiveDateFieldName = "Receive_Date";
        const string ReceivedQuantityFieldName = "Received_Quantity";
        //RE_Color & RE_Size table

        const string REColorTableName = "RE_Color";
        const string RESizeTableName = "RE_Size";
        const string ColorIdFieldName = "Color_Id";
        const string DescriptionFieldName = "Description";
        const string SizeIdFieldName = "Size_Id";
        const string RnDescriptorFieldName = "Rn_Descriptor";
        const string ProductTableName = "Product";
        const string Symbol = "@";
        const string ProductSKUIdFieldName = "Product_SKU_Id";
        const string REProductSKUTableName = "RE_Product_SKU";
        const string REProductTypeFieldName = "RE_Product_Type";
        const string TransferQuantityFieldName = "Transfer_Quantity";
        const string PendingInvTransferProductforTransferIdQueryName = "RE Pending InvTransfer Product for Inv Transfer Id?";

        //Secondary segment
        const string InventoryTransferProductSegment = "RE_Inv_Transfer_Product_RE_Inv";

        //ld strings
        const string ProductNotFound = "Product Not found";
        const string InventoryNotFound = "Inventory Not Found";

        //Client forms
        const string REGoodsIssueClientForm = "RE_Goods_Issue";
        const string REGoodsReceiveClientForm = "RE_Goods_Receive";
        const string RENewGoodsReceiveTemp = "RE_New_Goods_Receive(Temp)";

        bool popupShown = false;
        int previousQuantity, oldQty = 1;
        string previousStatus = string.Empty;
        #endregion

        #region Constructor

        public RE_Inventory_Transfer()
        {
            this.DefaultResourceBundleName = "RE_Inventory_Transfer";
        }

        #endregion

        #region Public methods

        public override void OnFormInitialized()
        {
            try
            {
                base.OnFormInitialized();
                this.SharedLoad();
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc, true);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Enable">Enable form?</param>
        /// <param name="EnableCopy">Enable Copy Button?</param>
        private void EnableDisableFormIncludingButtons(bool Enable,bool EnableCopy)
        {
            Pcm.Retail.Client.Globals.EnableDisableAllPrimaryFields(Enable);
            this.FormControl.GetControlByName("btnCreateNewGI").Enabled = Enable;
            this.FormControl.GetControlByName("btnRemoveItems").Enabled = Enable;
            //this.FormControl.GetControlByName("btnPrintGoods").Enabled = EnableCopy;
            this.FormControl.GetControlByName("btnCreateCopy").Enabled = EnableCopy;
        }

        public override void OnFormReloaded()
        {
            try
            {
                if (this.FormView.FormName.Equals("RE_RMA"))
                {
                    this.SharedLoad();
                }
                else
                {
                    string formName = string.Empty;

                    Id fromStorageLocId = Id.Create(Globals.SqlIndex("RE_Inventory_Transfer", "From_Storage_Location_Id", this.RecordId));
                    Id ToStorageLocId = Id.Create(Globals.SqlIndex("RE_Inventory_Transfer", "To_Storage_Location_Id", this.RecordId));
                    Id currEmpStore = Id.Create(Globals.SqlIndex("Employee", "RE_Store_Id", Globals.SystemClient.UserProfile.EmployeeId));
                    Id currEmpstorageLocationId = null;
                    DataTable storageLoc = Globals.GetDataTable("RE Storage Location For Primary Locations ?",
                                                new object[] { currEmpStore }, new string[] { "RE_Storage_Location_Id" });
                    if (storageLoc != null)
                    {
                        if (storageLoc.Rows.Count > 0)
                        {
                            currEmpstorageLocationId = Id.Create(storageLoc.Rows[0]["RE_Storage_Location_Id"]);
                        }
                    }
                    //RA:23/Aug/2012:Change for Mobile System:Start:
                    if (this.FormView.FormName.Equals(RENewGoodsReceiveTemp))
                        formName = RENewGoodsReceiveTemp;
                    //RA:23/Aug/2012:Change for Mobile System:End:
                    else
                    {
                        //DS:11012013 - Workflow change for Admin/Operations user.
                        if (Pcm.Retail.Client.Globals.CurrentUserInSecurityGroup("Retail POS"))
                        {
                            if (currEmpstorageLocationId.Equals(fromStorageLocId))
                                formName = REGoodsIssueClientForm;
                            else if (currEmpstorageLocationId.Equals(ToStorageLocId))
                                formName = REGoodsReceiveClientForm;
                            else
                                formName = REGoodsIssueClientForm;
                        }
                        else if (Pcm.Retail.Client.Globals.CurrentUserInSecurityGroup("Retail Administrator") ||
                            Pcm.Retail.Client.Globals.CurrentUserInSecurityGroup("Retail Operations"))
                        {
                            string status = TypeConvert.ToString(PrimaryDataRow[Status.FieldName]);
                            if (String.Equals(status, Status.Received) || String.Equals(status, Status.Cancel))
                                formName = REGoodsReceiveClientForm;
                            else if (String.Equals(status, Status.New) || String.Equals(status, Status.Hold))
                                formName = REGoodsIssueClientForm;
                            else if (String.Equals(status, Status.Pending) || String.Equals(status, Status.Issued))
                                formName = this.FormView.FormName;
                        }
                        else
                            formName = REGoodsIssueClientForm;
                    }
                    if (this.FormView.FormName != formName)
                    {
                        Globals.ShowForm(formName, this.RecordId);
                        return;
                    }
                    else
                        this.SharedLoad();
                    //deletedDT = null;
                }
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc, true);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override bool SaveRecord()
        {
            try
            {
                if (this.FormView.FormName.Equals("RE_RMA"))
                {
                    bool blnsave = false;
                    string message = string.Empty;
                    object emailSent= null;
                    string originalStatus = string.Empty;
                    DataTable primaryRow = this.FormData.DataSet.Tables[0];
                    DataTable invTransferProducts = this.FormData.DataSet.Tables[InventoryTransferProductSegment];
                    List<Id> supplierId = (from myRow in invTransferProducts.AsEnumerable()
                                               select Id.Create(myRow.Field<byte[]>("Product_Id__RE_Supplier_Id"))).Distinct().ToList();

                    if (this.RecordId != null)
                    {
                        originalStatus = TypeConvert.ToString(this.PrimaryDataRow["RMA_Status", DataRowVersion.Original]);
                    }
                    

                    //var supplierId = (from myRow in transferProduct.AsEnumerable()
                    //                  select Id.Create(myRow.Field<byte[]>("Product_Id__RE_Supplier_Id"))).Distinct();

                    ////for (int i = 0; i <= supplierId.Count() - 1; i++)
                    ////{
                    ////}
                    //foreach (object tempId in supplierId)
                    //{
                    //   // IEnumerable<DataRow> query = from order in transferProduct.AsEnumerable()
                    //   //                              where Id.Create(order.Field<byte[]>("Product_Id__RE_Supplier_Id")) == Id.Create(tempId)
                    //   //                              select order;
                    //   // DataTable prods = Globals.GetDataTable("RE_Inv_Transfer_Product", new string[] { });
                    //   // prods = transferProduct.Copy();
                    //   //query.CopyToDataTable<DataRow>(prods,LoadOption.Upsert);

                    //    DataTable primaryRow = this.FormData.DataSet.Tables[0];

                    //    this.SystemClient.ExecuteServerTask("RE_Inventory_Transfer", "CreateInventoryTransfer", new Type[] { typeof(DataTable), typeof(Id), typeof(DataTable) },
                    //                                                                       new object[] { primaryRow, Id.Create(tempId), transferProduct });
                    //}

                    //this.FormView.CloseForm(true);
                    //return false;
                    if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["RMA_Status"]), "Issued"))
                    {
                        if (invTransferProducts == null || invTransferProducts.Rows.Count == 0)
                        {
                            PivotalMessageBox.Show("RMA can be issued only if it has transfer products.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }
                    }

                    try
                    {
                        blnsave = base.SaveRecord();
                    }
                    catch(Exception ex)
                    {
                        if (ex.Message.Contains("The field 'Reason' in the segment 'RE_Inv_Transfer_Product_RE_Inv' is a required field.  Please enter a valid value"))
                        {
                            PivotalMessageBox.Show("Unable to save the form data. Provide a value for all required fields.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return false;
                        }
                        else
                        {
                            Globals.HandleException(ex, true);
                        }
                    }
                    
                    
                    string currentStatusValue = TypeConvert.ToString(this.PrimaryDataRow["RMA_Status"]);
                    if (currentStatusValue == Status.Issued && currentStatusValue!=originalStatus)
                    {
                        if (supplierId.Count() > 1)
                        {
                            for (int i = 0; i < supplierId.Count() - 1; i++)
                            {
                                object newRMARecord = this.SystemClient.ExecuteServerTask("RE_Inventory_Transfer", "CreateInventoryTransfer", new Type[] { typeof(DataTable), typeof(Id), typeof(Id) },
                                                                                               new object[] { primaryRow, Id.Create(supplierId[i]), this.RecordId });

                                emailSent = this.SystemClient.ExecuteServerTask("RE_Inventory_Transfer", "CreateReport", new Type[] { typeof(Id) },
                                                                                              new object[] { Id.Create(newRMARecord) }); 
                                if (!TypeConvert.ToBoolean(emailSent))
                                {
                                    string supplierName = TypeConvert.ToString(Globals.SqlIndex("Company", "Company_Name", supplierId[i]));
                                    PivotalMessageBox.Show("Email cannot be sent to the Supplier "+ supplierName,
                                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                }
                            }

                        }
                        
                        this.SystemClient.ExecuteServerTask("RE_Inventory_Transfer", "updatePrimary", new Type[] { typeof(Id), typeof(Id) },
                                                                                              new object[] { this.RecordId, Id.Create(supplierId[supplierId.Count() - 1]) });

                        emailSent = this.SystemClient.ExecuteServerTask("RE_Inventory_Transfer", "CreateReport", new Type[] { typeof(Id)},
                                                                                              new object[] { this.RecordId });
                        if (!TypeConvert.ToBoolean(emailSent))
                        {
                            string supplierName = TypeConvert.ToString(Globals.SqlIndex("Company", "Company_Name", supplierId[supplierId.Count() - 1]));
                            PivotalMessageBox.Show("Email cannot be sent to the Supplier " + supplierName,
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                        //this.SystemClient.ExecuteServerTask("RE_Inventory_Transfer", "processInventory", new Type[] { typeof(string), typeof(string), typeof(object) },
                        //                                                                   new object[] { "RMA", "Issue", TypeConvert.ToDBValue(this.RecordId) });
                        //this.SystemClient.ExecuteServerTask("RE_Inventory_Transfer", "CreateReport", new Type[] { typeof(object) },
                        //                                                                   new object[] { TypeConvert.ToDBValue(this.RecordId) });
                    }
                    return blnsave;
                }
                else
                {
                    Int32 issuedQuantity = 0;
                    Int32 receivedQuantity = 0;
                    string currentStatusValue = TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]);
                    string origStatusValue = string.Empty;

                    if (this.RecordId != null)
                        origStatusValue = TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName, DataRowVersion.Original]);

                    //NN 27 March 2012:Issue 77
                    //Added .DefaultView.ToTable() so that deleted rows are not considered.
                    DataTable transferProduct = this.FormData.DataSet.Tables[InventoryTransferProductSegment];//.DefaultView.ToTable();

                    if (transferProduct != null && transferProduct.Rows.Count > 0)
                    {
                        bool setReceiveStatus = true;
                        for (int i = 0; i < transferProduct.Rows.Count; i++)
                        {
                            if (transferProduct.Rows[i].RowState != DataRowState.Deleted && !TypeConvert.ToBoolean(transferProduct.Rows[i]["Marked_As_Delete"]))
                            {
                                if (!TypeConvert.ToBoolean(transferProduct.Rows[i]["Received"]))
                                    setReceiveStatus = false;
                            }
                        }

                        if (setReceiveStatus)
                        {
                            PivotalMessageBox.Show("The status will be set to 'Received'.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            this.PrimaryDataRow[Status.FieldName] = Status.Received;
                        }

                        if (this.FormView.FormName == REGoodsIssueClientForm)
                        {
                            for (int i = 0; i < transferProduct.Rows.Count; i++)
                            {
                                //DS:15102012 - Including Marked_As_Delete flag in calculation of the Quantity.
                                //if (transferProduct.Rows[i].RowState != DataRowState.Deleted)
                                if (transferProduct.Rows[i].RowState != DataRowState.Deleted && !TypeConvert.ToBoolean(transferProduct.Rows[i]["Marked_As_Delete"]))
                                {
                                    if (TypeConvert.ToInt32(transferProduct.Rows[i][QuantityIssuedFieldName]) > 0)
                                        issuedQuantity = issuedQuantity + TypeConvert.ToInt32(transferProduct.Rows[i][QuantityIssuedFieldName]);
                                }
                            }
                            this.PrimaryDataRow[TransferQuantityFieldName] = issuedQuantity;

                            //NN 06 April 2012:Issue No 99:
                            //Goods Issue status should be changed to Hold if the Status is "New".
                            //Also prompting same in message to the user.
                            if (currentStatusValue == Status.New)
                            {
                                PivotalMessageBox.Show("The status will be set to 'Hold'.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                this.PrimaryDataRow[Status.FieldName] = Status.Hold;
                            }
                        }
                        else if (this.FormView.FormName == REGoodsReceiveClientForm)
                        {
                            for (int i = 0; i < transferProduct.Rows.Count; i++)
                            {
                                //DS:31102012 - Including Marked_As_Delete flag in calculation of the Quantity.
                                if (transferProduct.Rows[i].RowState != DataRowState.Deleted && !TypeConvert.ToBoolean(transferProduct.Rows[i]["Marked_As_Delete"]))
                                {
                                    if (TypeConvert.ToInt32(transferProduct.Rows[i]["Quantity_Received"]) > 0)
                                        receivedQuantity = receivedQuantity + TypeConvert.ToInt32(transferProduct.Rows[i]["Quantity_Received"]);
                                }
                            }
                            if (receivedQuantity > 0)
                            {
                                this.PrimaryDataRow[ReceivedQuantityFieldName] = receivedQuantity;
                            }
                        }
                    }
                    else 
                    {
                        if (currentStatusValue == Status.New)
                        {
                            PivotalMessageBox.Show("The status will be set to 'Hold'.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            this.PrimaryDataRow[Status.FieldName] = Status.Hold;
                        }
                    }
                    //this.DataSet.AcceptChanges();
                    //if (deletedDT != null)
                    //    this.TransitionPointParameter.SetUserDefinedParameter(1, deletedDT);
                    if (this.RecordId != null && TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]) == Status.Received
                        && TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]) != origStatusValue)
                    {
                        this.DataSet.AcceptChanges();
                        this.TransitionPointParameter.SetUserDefinedParameter(1, transferProduct);
                    }

                    this.PrimaryDataRow["RE_Serial_Number"] = DBNull.Value;
                    this.PrimaryDataRow["RE_Product_Serial_No_Id"] = DBNull.Value;
                    this.PrimaryDataRow["Product_Barcode"] = DBNull.Value;
                    this.PrimaryDataRow["Product_Id"] = DBNull.Value;

                    ((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Product_Serial_No_Id")).ReadOnly = true;
                    ((PivotalTextBox)this.FormControl.GetControlByDataName("RE_Serial_Number")).ReadOnly = true;
                    //Pcm.Retail.Client.Globals.EnableDisablePrimaryFields(false, new string[] { "RE_Serial_Number", "RE_Product_Serial_No_Id" });

                    //this.PrimaryDataRow["Receive_Batch_ID"] = DBNull.Value;

                    if (this.FormView.FormName == REGoodsReceiveClientForm)
                    {
                        DataTable transferProductRecBatch = Globals.GetDataTable("RE Inv Transfer Rec Batch for InvTransfer Id?", new object[] { this.RecordId }, new string[] { });
                        DataTable transProdRecBatch = this.FormData.DataSet.Tables["RE_Inv_Trnsf_Rec_Batch_Invento"];
                        if (transferProduct != null && transferProduct.Rows.Count > 0)
                        {
                            if (transProdRecBatch != null && transProdRecBatch.Rows.Count > 0)
                            {
                                if (Convert.ToInt32(this.PrimaryDataRow[ReceivedQuantityFieldName]) != (transferProductRecBatch.Rows.Count + transProdRecBatch.Rows.Count))
                                {
                                    PivotalMessageBox.Show("Total Quantity Received and the items added to the grid do not match. Please close and reopen the record.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                    return false;
                                }
                            }
                        }
                    }


                    bool blnSave = base.SaveRecord();
                    if (this.FormView.FormName == REGoodsIssueClientForm)
                    {
                        if (currentStatusValue == Status.Issued && currentStatusValue != origStatusValue)
                        {
                            //Create Inventory Movements 
                            //this.SystemClient.ExecuteServerTask("RE_Inventory_Transfer", "CreateTransferMovementForIssuedRecords", new Type[] { typeof(object), typeof(bool) },
                            //                                                               new object[] { TypeConvert.ToDBValue(this.RecordId), false });
                            this.SystemClient.ExecuteServerTask("RE_Inventory_Transfer", "processInventory", new Type[] { typeof(string), typeof(string), typeof(object) },
                                                                                           new object[] { "Inventory Transfer", "Issued", TypeConvert.ToDBValue(this.RecordId) });
                            DataTable primaryRow = this.FormData.DataSet.Tables[0];
                            this.SystemClient.ExecuteServerTask("RE_Inventory_Transfer", "CreateInventoryTransferSerial", new Type[] { typeof(object), typeof(DataTable) },
                                                                                           new object[] { TypeConvert.ToDBValue(this.RecordId), primaryRow });
                        }
                        else if (currentStatusValue == Status.Cancel && currentStatusValue != origStatusValue)
                        {
                            //Create Inventory Movements 
                            //this.SystemClient.ExecuteServerTask("RE_Inventory_Transfer", "CreateTransferMovementForIssuedRecords", new Type[] { typeof(object), typeof(bool) },
                            //                                                               new object[] { TypeConvert.ToDBValue(this.RecordId), true });
                        }
                    }

                    //if (this.FormView.FormName == REGoodsReceiveClientForm)
                    //{

                    //    if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "PO Receive"))
                    //    {
                    //        try
                    //        {
                    //            this.SystemClient.ExecuteServerTask("RE_Inventory_Transfer", "processInventory", new Type[] { typeof(string), typeof(string), typeof(object) },
                    //                                                                           new object[] { "PO Receive", "Received", TypeConvert.ToDBValue(this.RecordId) });
                    //        }
                    //        catch(Exception ex)
                    //        {
                    //            System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
                    //            el.Log = "Pivotal";
                    //            var result = (from System.Diagnostics.EventLogEntry elog in el.Entries
                    //                          where (elog.TimeGenerated >= DateTime.Now - new TimeSpan(0,3,0))
                    //                          && (elog.InstanceId == 999)
                    //                          orderby elog.TimeGenerated descending
                    //                          select elog).First();

                    //            if (result != null)
                    //            {

                    //            }
                    //        }
                    //    }
                    //    else if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "Inventory Receive"))
                    //    {
                    //        this.SystemClient.ExecuteServerTask("RE_Inventory_Transfer", "processInventory", new Type[] { typeof(string), typeof(string), typeof(object) },
                    //                                                                       new object[] { "Inventory Receive", "Received", TypeConvert.ToDBValue(this.RecordId) });
                    //    }
                    //    else if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "Inventory Transfer"))
                    //    {
                    //        this.SystemClient.ExecuteServerTask("RE_Inventory_Transfer", "processInventory", new Type[] { typeof(string), typeof(string), typeof(object) },
                    //                                                                       new object[] { "Inventory Transfer", "Received", TypeConvert.ToDBValue(this.RecordId) });
                    //    }
                    //}

                    return blnSave;
                }
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc, true);
                return false;
            }
        }


        /// <summary>
        /// New record
        /// </summary>
        /// <param name="secondaryName"></param>
        /// <returns></returns>
        //public override bool NewSecondaryRecord(string secondaryName)
        //{
        //    try
        //    {
        //        if (secondaryName == InventoryTransferProductSegment)
        //        {
        //            this.FormView.Dirty = false;
        //            return false;
        //        }
        //        else
        //        {
        //            if (TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]) == Status.Cancel)
        //            {
        //                this.FormView.Dirty = false;
        //                return false;
        //            }
        //            else
        //                return base.NewSecondaryRecord(secondaryName);
        //        }
        //    }
        //    catch (Exception exc)
        //    {
        //        Globals.HandleException(exc, true);
        //        return false;
        //    }
        //}
        #endregion

        #region Private Methods

        private void SharedLoad()
        {
            try
            {
                if (this.FormView.FormName.Equals("RE_RMA"))
                {
                    object cashierStaffId = null;
                    if (this.RecordId == null)
                    {
                        cashierStaffId = IsCashierLogin();
                        if (!(Pcm.Retail.Client.Globals.CurrentUserInSecurityGroup("Retail Administrator")
                            || Pcm.Retail.Client.Globals.CurrentUserInSecurityGroup("Retail Operations")) && Convert.IsDBNull(cashierStaffId))
                        {
                            this.FormView.CloseForm(true);
                            if (PivotalMessageBox.Show("No Cashier found logged in to the POS.", MessageBoxButtons.OK, MessageBoxIcon.Warning) == DialogResult.OK)
                                Globals.NewForm("RE_Cashier_Log", null);
                            return;
                        }

                        this.ButtonBar.Buttons.Remove(this.ButtonBar.Buttons["Apply"]);
                        Id currEmpStore = Id.Create(Globals.SqlIndex("Employee", "RE_Store_Id", Globals.SystemClient.UserProfile.EmployeeId));
                        DataTable curEmpStorageLoc = Globals.GetDataTable("RE Storage Location For Primary Locations ?",
                                                            new object[] { currEmpStore }, new string[] { "RE_Storage_Location_Id" });

                        if (curEmpStorageLoc != null && curEmpStorageLoc.Rows.Count > 0)
                        {
                            this.PrimaryDataRow[FromStorageLocationIdFieldName] = curEmpStorageLoc.Rows[0]["RE_Storage_Location_Id"];
                        }

                        DataTable tostorageLoc = Globals.GetDataTable("RE Storage Location with Store Id and Type as RMA?", new object[] { currEmpStore },
                            new string[] { "RE_Storage_Location_Id" });
                        if (tostorageLoc != null && tostorageLoc.Rows.Count > 0)
                        {
                            this.PrimaryDataRow[ToStorageLocationIdFieldName] = tostorageLoc.Rows[0]["RE_Storage_Location_Id"];
                        }

                        this.PrimaryDataRow["RMA_Status"] = "Issued";
                        this.PrimaryDataRow["Transfer_Type"] = "RMA";
                        this.PrimaryDataRow[FromStaffIdFieldName] = cashierStaffId;
                        ((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Supplier_Id")).Visible = false;
                        this.FormControl.GetControlByName("lblRESupplierId").Visible = false;
                        //Pcm.Retail.Client.Globals.EnableDisableSecondaryFields(true, "RE_Inv_Transfer_Product_RE_Inv", "Reason");
                    }
                    else
                    {
                        if (SystemClient.SystemInformation.IsMobile && !Pcm.Retail.Client.Globals.IsMasterPOS)
                        {
                            if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["RMA_Status"]), "Cancelled") ||
                                    String.Equals(TypeConvert.ToString(this.PrimaryDataRow["RMA_Status"]), "Collected"))
                            {
                                Pcm.Retail.Client.Globals.EnableDisableAllPrimaryFields(false);
                            }
                            else
                            {
                                this.FormView.CloseForm(true);
                                PivotalMessageBox.Show("This feature is not available Offline when POS is not Master POS.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                return;
                            }
                        }
                        Id currEmpStore = Id.Create(Globals.SqlIndex("Employee", "RE_Store_Id", Globals.SystemClient.UserProfile.EmployeeId));
                        DataTable curEmpStorageLoc = Globals.GetDataTable("RE Storage Location For Primary Locations ?",
                                                            new object[] { currEmpStore }, new string[] { "RE_Storage_Location_Id" });
                        if (curEmpStorageLoc != null && curEmpStorageLoc.Rows.Count > 0)
                        {
                            if (Id.Create(this.PrimaryDataRow["From_Storage_Location_Id"]) == Id.Create(curEmpStorageLoc.Rows[0]["RE_Storage_Location_Id"]))
                            //&& (Pcm.Retail.Client.Globals.CurrentUserInSecurityGroup("Retail POS")))
                            {
                                if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["RMA_Status"]), "Cancelled") ||
                                    String.Equals(TypeConvert.ToString(this.PrimaryDataRow["RMA_Status"]), "Collected"))
                                {
                                    Pcm.Retail.Client.Globals.EnableDisableAllPrimaryFields(false);
                                    this.FormControl.GetControlByName("btnPrintRMA").Enabled = true;
                                }
                                else
                                {
                                    cashierStaffId = IsCashierLogin();
                                    if (!(Pcm.Retail.Client.Globals.CurrentUserInSecurityGroup("Retail Administrator")
                                        || Pcm.Retail.Client.Globals.CurrentUserInSecurityGroup("Retail Operations")) && Convert.IsDBNull(cashierStaffId))
                                    {
                                        this.FormView.CloseForm(true);
                                        if (PivotalMessageBox.Show("No Cashier found logged in to the POS.", MessageBoxButtons.OK, MessageBoxIcon.Warning) == DialogResult.OK)
                                            Globals.NewForm("RE_Cashier_Log", null);
                                        return;
                                    }
                                    Pcm.Retail.Client.Globals.EnableDisableAllPrimaryFields(false);
                                    this.FormControl.GetControlByName("btnPrintRMA").Enabled = true;
                                    Pcm.Retail.Client.Globals.EnableDisablePrimaryFields(true, new string[] { "RMA_Status" });
                                }
                            }
                        }

                        ((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Supplier_Id")).Visible = true;
                        this.FormControl.GetControlByName("lblRESupplierId").Visible = true;
                        this.FormView.Dirty = false;

                    }
                }
                else
                {
                    if (this.FormView.FormName == "RE_Goods_Receive" && !String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Status"]), "Received"))
                    {
                        if (Convert.IsDBNull(this.PrimaryDataRow["Receive_Batch_Increment"]))
                        {
                            this.PrimaryDataRow["Receive_Batch_Increment"] = 1;
                        }
                        else
                        {
                            this.PrimaryDataRow["Receive_Batch_Increment"] = TypeConvert.ToInt32(this.PrimaryDataRow["Receive_Batch_Increment"]) + 1;
                        }
                    }
                    if (this.FormView.FormName == "RE_Goods_Issue")
                    {
                        if (this.RecordId == null)
                        {   
                            this.PrimaryDataRow["Transfer_Type"] = "Inventory Transfer";
                            Id currEmpStore1 = Id.Create(Globals.SqlIndex("Employee", "RE_Store_Id", Globals.SystemClient.UserProfile.EmployeeId));
                            DataTable curEmpStorageLoc1 = Globals.GetDataTable("RE Storage Location For Primary Locations ?",
                                                                new object[] { currEmpStore1 }, new string[] { "RE_Storage_Location_Id" });
                            if (curEmpStorageLoc1 != null && curEmpStorageLoc1.Rows.Count > 0)
                            {
                                this.PrimaryDataRow[FromStorageLocationIdFieldName] = curEmpStorageLoc1.Rows[0]["RE_Storage_Location_Id"];
                            }
                        }
                        this.PrimaryDataRow["Receive_Batch_ID"] = 
                            TypeConvert.ToString(Guid.NewGuid());
                    }
                    if (this.FormView.FormName == "RE_Goods_Receive" && !String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Status"]), "Received"))
                    {
                        this.PrimaryDataRow["Receive_Batch_ID"] = TypeConvert.ToString(this.PrimaryDataRow["Transfer_ID"]) + "-" + TypeConvert.ToString(this.PrimaryDataRow["Receive_Batch_Increment"]);
                            //TypeConvert.ToString(Guid.NewGuid());
                    }
                    Id currEmpStore = Id.Create(Globals.SqlIndex("Employee", "RE_Store_Id", Globals.SystemClient.UserProfile.EmployeeId));
                    DataTable curEmpStorageLoc = Globals.GetDataTable("RE Storage Location For Primary Locations ?",
                                                        new object[] { currEmpStore }, new string[] { "RE_Storage_Location_Id" });
                    object cashierStaffId = IsCashierLogin();
                    if (this.RecordId == null)
                    {
                        //DS:07012013 - If logged in user belongs to Administrator or Operations Group:
                        //•	Skip Cashier Login Check
                        if (!(Pcm.Retail.Client.Globals.CurrentUserInSecurityGroup("Retail Administrator")
                            || Pcm.Retail.Client.Globals.CurrentUserInSecurityGroup("Retail Operations")) && Convert.IsDBNull(cashierStaffId))
                        {
                            this.FormView.CloseForm(true);
                            if (PivotalMessageBox.Show("No Cashier found logged in to the POS.", MessageBoxButtons.OK, MessageBoxIcon.Warning) == DialogResult.OK)
                                Globals.NewForm("RE_Cashier_Log", null);
                            return;
                        }
                        else
                        {
                            //DS:07012013 - Open the From Staff Id field for manual fill-up if the user belongs to Admin or Operations security group for new GI.
                            if (this.FormView.FormName == REGoodsIssueClientForm)
                            {
                                if (Pcm.Retail.Client.Globals.CurrentUserInSecurityGroup("Retail Administrator")
                                    || Pcm.Retail.Client.Globals.CurrentUserInSecurityGroup("Retail Operations"))
                                {
                                    ((PivotalForeignKey)this.FormControl.GetControlByDataName(FromStaffIdFieldName)).ReadOnly = false;
                                    ((PivotalForeignKey)this.FormControl.GetControlByDataName(FromStaffIdFieldName)).Required = true;
                                }
                                else
                                {
                                    ((PivotalForeignKey)this.FormControl.GetControlByDataName(FromStaffIdFieldName)).ReadOnly = true;
                                    ((PivotalForeignKey)this.FormControl.GetControlByDataName(FromStaffIdFieldName)).Required = false;
                                }
                            }

                            //DS:07012013 - Set the To_Staff_Id instead of From_Staff_Id as in case of Temp form. 
                            //There is no new GR, so that case is not covered.
                            //this.PrimaryDataRow[FromStaffIdFieldName] = cashierStaffId;
                            if (this.FormView.FormName == RENewGoodsReceiveTemp)
                                this.PrimaryDataRow[ToStaffIdFieldName] = cashierStaffId;
                            else if (this.FormView.FormName == REGoodsIssueClientForm)
                                this.PrimaryDataRow[FromStaffIdFieldName] = cashierStaffId;
                        }
                        if (this.FormView.FormName == RENewGoodsReceiveTemp)
                        {
                            if (curEmpStorageLoc != null && curEmpStorageLoc.Rows.Count > 0)
                                this.PrimaryDataRow[ToStorageLocationIdFieldName] = curEmpStorageLoc.Rows[0]["RE_Storage_Location_Id"];
                        }
                        else
                        {
                            if (TypeConvert.ToBoolean(this.PrimaryDataRow["DisconnDelete_PendingItems"]) == true)
                                this.FormView.Dirty = true;
                        }
                    }
                    else
                    {
                        switch (this.FormView.FormName)
                        {
                            case REGoodsIssueClientForm:
                                if (SystemClient.SystemInformation.IsMobile && !Pcm.Retail.Client.Globals.IsMasterPOS)
                                {
                                    this.FormView.CloseForm(true);
                                    PivotalMessageBox.Show("This feature is not available Offline when POS is not Master POS.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    return;
                                }
                                //Fetch the current Store.
                                if (curEmpStorageLoc != null && curEmpStorageLoc.Rows.Count > 0)
                                {
                                    if (Id.Create(this.PrimaryDataRow["From_Storage_Location_Id"]) == Id.Create(curEmpStorageLoc.Rows[0]["RE_Storage_Location_Id"]))
                                    {
                                        if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Status"]), Status.Cancel) ||
                                            String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Status"]), Status.Received))
                                            EnableDisableFormIncludingButtons(false, true);
                                        else
                                        {
                                            //DS:07012013 - If logged in user belongs to Administrator or Operations Group:
                                            //•	Skip Cashier Login Check
                                            if (!(Pcm.Retail.Client.Globals.CurrentUserInSecurityGroup("Retail Administrator")
                                                || Pcm.Retail.Client.Globals.CurrentUserInSecurityGroup("Retail Operations")) && Convert.IsDBNull(cashierStaffId))
                                            {
                                                this.FormView.CloseForm(true);
                                                if (PivotalMessageBox.Show("No Cashier found logged in to the POS.", MessageBoxButtons.OK, MessageBoxIcon.Warning) == DialogResult.OK)
                                                    Globals.NewForm("RE_Cashier_Log", null);
                                                return;
                                            }
                                            else
                                            {
                                                if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Status"]), Status.Issued))
                                                    EnableDisableFormIncludingButtons(false, true);
                                                else if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Status"]), Status.Pending))
                                                {
                                                    this.FormControl.GetControlByName("btnCreateNewGI").Enabled = true;
                                                    this.FormControl.GetControlByName("btnRemoveItems").Enabled = true;
                                                    //DS:08112012 - When opening Pending records, the following fields must be read-only.
                                                    Pcm.Retail.Client.Globals.EnableDisablePrimaryFields(false, new string[] { "From_Storage_Location_Id", 
                                                    "To_Storage_Location_Id", "Scanner_Issue_No", "Product_Barcode", "Product_Id" });
                                                }
                                                //DS:08112012 - When opening Hold records, the following fields must be non read-only.
                                                else if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Status"]), Status.Hold))
                                                {
                                                    //DS:09012013 - When opening an existing GI record, it should not overwrite the existing From Staff field value when 
                                                    //the status is other than Hold.
                                                    if (!Convert.IsDBNull(cashierStaffId))
                                                        this.PrimaryDataRow[FromStaffIdFieldName] = cashierStaffId;
                                                    Pcm.Retail.Client.Globals.EnableDisablePrimaryFields(true, new string[] { "From_Storage_Location_Id", 
                                                       "To_Storage_Location_Id", "Scanner_Issue_No", "Product_Barcode", "Product_Id" });
                                                }
                                                //DS:09012013 - For administrator/operations user the From Staff field should stay enabled.
                                                if ((Pcm.Retail.Client.Globals.CurrentUserInSecurityGroup("Retail Administrator")
                                                    || Pcm.Retail.Client.Globals.CurrentUserInSecurityGroup("Retail Operations")) &&
                                                    (TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]) == Status.Hold))
                                                {
                                                    this.FormControl.GetControlByDataName(FromStaffIdFieldName).Enabled = true;
                                                    ((PivotalForeignKey)this.FormControl.GetControlByDataName(FromStaffIdFieldName)).ReadOnly = false;
                                                    ((PivotalForeignKey)this.FormControl.GetControlByDataName(FromStaffIdFieldName)).Required = true;
                                                }
                                                else
                                                {
                                                    ((PivotalForeignKey)this.FormControl.GetControlByDataName(FromStaffIdFieldName)).ReadOnly = true;
                                                    ((PivotalForeignKey)this.FormControl.GetControlByDataName(FromStaffIdFieldName)).Required = false;
                                                }

                                                Pcm.Retail.Client.Globals.EnableDisablePrimaryFields(true, "Status");
                                                this.FormView.Dirty = false;
                                            }
                                        }
                                    }
                                    else
                                        EnableDisableFormIncludingButtons(false, false);
                                }
                                this.FormView.Dirty = false;
                                break;
                            case REGoodsReceiveClientForm:
                                this.PrimaryDataRow["Received_Quantity_PerBatch"] = 0;
                                if (SystemClient.SystemInformation.IsMobile && !Pcm.Retail.Client.Globals.IsMasterPOS)
                                {
                                    if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Status"]), Status.Cancel) ||
                                            String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Status"]), Status.Received) ||
                                    String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Status"]), "Received with Deficit"))
                                    {
                                        Pcm.Retail.Client.Globals.EnableDisableAllFields(false);
                                    }
                                    else
                                    {
                                        this.FormView.CloseForm(true);
                                        PivotalMessageBox.Show("This feature is not available Offline when POS is not Master POS.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                        return;
                                    }
                                }
                                if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "PO Receive"))
                                {
                                    ((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Supplier_Id")).Visible = true;
                                    this.FormControl.GetControlByName("lblRESupplierId").Visible = true;
                                    this.FormControl.GetControlByDataName("RE_Supplier_Code").Visible = true;
                                    this.FormControl.GetControlByName("lblRESupplierCode").Visible = true;
                                    this.FormControl.GetControlByDataName("RE_External_PO_Number").Visible = true;
                                    this.FormControl.GetControlByName("lblREExternalPONumber1").Visible = true;
                                    this.FormControl.GetControlByDataName("RE_External_PO_Number").Visible = true;
                                    this.FormControl.GetControlByName("lblPOReferenceNumber").Visible = true;
                                }
                                else
                                {
                                    ((PivotalForeignKey)this.FormControl.GetControlByDataName("RE_Supplier_Id")).Visible = false;
                                    this.FormControl.GetControlByName("lblRESupplierId").Visible = false;
                                    this.FormControl.GetControlByDataName("RE_Supplier_Code").Visible = false;
                                    this.FormControl.GetControlByName("lblRESupplierCode").Visible = false;
                                    this.FormControl.GetControlByDataName("PO_Reference_Number").Visible = false;
                                    this.FormControl.GetControlByName("lblREExternalPONumber1").Visible = false;
                                    this.FormControl.GetControlByDataName("RE_External_PO_Number").Visible = false;
                                    this.FormControl.GetControlByName("lblPOReferenceNumber").Visible = false;
                                }

                                if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "Inventory Transfer"))
                                {
                                    this.FormControl.GetControlByDataName("Disconn_ReceivedWithDeficit").Visible = true;
                                    this.FormControl.GetControlByName("ReceiveWithDeficit").Visible = true;
                                }
                                else
                                {
                                    this.FormControl.GetControlByDataName("Disconn_ReceivedWithDeficit").Visible = false;
                                    this.FormControl.GetControlByName("ReceiveWithDeficit").Visible = false;
                                }
                                if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Status"]), Status.Cancel) ||
                                            String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Status"]), Status.Received)||
                                    String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Status"]), "Received with Deficit")||
                                    String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Status"]),Status.Hold))
                                {
                                    Pcm.Retail.Client.Globals.EnableDisableAllFields(false);
                                    this.FormControl.GetControlByName("PivotalButton1").Enabled = false;
                                }
                                else
                                {
                                    //DS:07012013 - If logged in user belongs to Administrator or Operations Group:
                                    //•	Skip Cashier Login Check
                                    if (!(Pcm.Retail.Client.Globals.CurrentUserInSecurityGroup("Retail Administrator")
                                        || Pcm.Retail.Client.Globals.CurrentUserInSecurityGroup("Retail Operations")) && Convert.IsDBNull(cashierStaffId))
                                    {
                                        this.FormView.CloseForm(true);
                                        if (PivotalMessageBox.Show("No Cashier found logged in to the POS.", MessageBoxButtons.OK, MessageBoxIcon.Warning) == DialogResult.OK)
                                            Globals.NewForm("RE_Cashier_Log", null);
                                        return;
                                    }
                                    else
                                    {
                                        //Pcm.Retail.Client.Globals.EnableDisableAllFields(true);
                                        if (TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]) == Status.Issued)
                                        {
                                            this.PrimaryDataRow[Status.FieldName] = Status.Pending;
                                            this.FormControl.GetControlByDataName(Status.FieldName).Enabled = false;
                                        }
                                        else if (TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]) == Status.Pending)
                                            this.FormControl.GetControlByDataName(Status.FieldName).Enabled = false;
                                        //DS:09012013 - When the cashier is not logged in for admin case, then do not reset the value.
                                        if (!Convert.IsDBNull(cashierStaffId))
                                            this.PrimaryDataRow[ToStaffIdFieldName] = cashierStaffId;
                                        this.PrimaryDataRow[ReceiveDateFieldName] = DateTime.Now;

                                        //DS:07012013 - For administrator/operations user Received checkbox will be enabled only for Statuses 'Pending' and 'Issued'.
                                        if (Pcm.Retail.Client.Globals.CurrentUserInSecurityGroup("Retail Administrator")
                                            || Pcm.Retail.Client.Globals.CurrentUserInSecurityGroup("Retail Operations") &&
                                            (TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]) == Status.Issued ||
                                            TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]) == Status.Pending))
                                        {
                                            Pcm.Retail.Client.Globals.EnableDisableSecondaryFields(true, InventoryTransferProductSegment, "Received");
                                            this.FormControl.GetControlByName("btnReceiveAll").Enabled = true;
                                            this.FormControl.GetControlByDataName(ToStaffIdFieldName).Enabled = true;
                                            ((PivotalForeignKey)this.FormControl.GetControlByDataName(ToStaffIdFieldName)).ReadOnly = false;
                                            ((PivotalForeignKey)this.FormControl.GetControlByDataName(ToStaffIdFieldName)).Required = true;
                                        }
                                        else
                                        {
                                            Pcm.Retail.Client.Globals.EnableDisableSecondaryFields(false, InventoryTransferProductSegment, "Received");
                                            this.FormControl.GetControlByName("btnReceiveAll").Enabled = false;
                                            ((PivotalForeignKey)this.FormControl.GetControlByDataName(ToStaffIdFieldName)).ReadOnly = true;
                                            ((PivotalForeignKey)this.FormControl.GetControlByDataName(ToStaffIdFieldName)).Required = false;
                                        }
                                        this.FormView.Dirty = false;
                                    }
                                }
                                this.FormView.Dirty = false;
                                break;
                            case RENewGoodsReceiveTemp:
                                if (Id.Create(this.PrimaryDataRow["To_Storage_Location_Id"]) == Id.Create(curEmpStorageLoc.Rows[0]["RE_Storage_Location_Id"]))
                                {
                                    if (Convert.IsDBNull(this.PrimaryDataRow["Link_Transfer_Id"]))
                                    {
                                        if (Convert.IsDBNull(cashierStaffId))
                                        {
                                            this.FormView.CloseForm(true);
                                            if (PivotalMessageBox.Show("No Cashier found logged in to the POS.", MessageBoxButtons.OK, MessageBoxIcon.Warning) == DialogResult.OK)
                                                Globals.NewForm("RE_Cashier_Log", null);
                                            return;
                                        }
                                        else
                                        {
                                            //Pcm.Retail.Client.Globals.EnableDisableAllFields(true);
                                            this.PrimaryDataRow[ToStaffIdFieldName] = cashierStaffId;
                                            this.FormView.Dirty = false;
                                        }
                                    }
                                    else
                                        Pcm.Retail.Client.Globals.EnableDisableAllFields(false);
                                }
                                else
                                    Pcm.Retail.Client.Globals.EnableDisableAllFields(false);
                                break;
                            default:
                                break;
                        }
                    }

                    //this.EnableControlsBasedOnStatus();
                    ((PivotalForeignKey)this.FormControl.GetControlByDataName(ProductSKUIdFieldName)).ReadOnly = true;

                    this.HighlightRows();
                }
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc, true);
            }
        }

        private void HighlightRows()
        {
            if (this.FormView.FormName != REGoodsReceiveClientForm)
                return;
            //color coding for non received items
            if (this.RecordId != null)
            {              
                PivotalSecondary pvtSecondary = this.FormControl.GetControlByName("RE_Inv_Transfer_Product_RE_Inventory_Transfer_Id") as PivotalSecondary;
                
                if (pvtSecondary.Rows.Count > 0)
                {
                    for (int i = 0; i < pvtSecondary.Rows.Count; i++)
                    {
                        //NN 30 March 2012:Issue 79:
                        //Added code to highlight color for NewTransfer secondary row
                        //if (TypeConvert.ToBoolean(pvtSecondary.Rows[i].Cells["GR_NewTransfer"].Value))
                        //{
                        //    pvtSecondary.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.YellowGreen;
                        //}
                        //else if (TypeConvert.ToBoolean(pvtSecondary.Rows[i].Cells["Received"].Value) == false || pvtSecondary.Rows[i].Cells["Received"].Value == DBNull.Value)
                        //{
                        //    pvtSecondary.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.OrangeRed;
                        //}
                        //DS: Generalised teh color based on the open quantity.
                        if (TypeConvert.ToInt32(pvtSecondary.Rows[i].Cells[QuantityOpenFieldName].Value) > 0)
                            pvtSecondary.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.YellowGreen;
                        else if (TypeConvert.ToInt32(pvtSecondary.Rows[i].Cells[QuantityOpenFieldName].Value) < 0)
                            pvtSecondary.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.OrangeRed;
                        else
                        {
                            if (i % 2 == 0)
                                pvtSecondary.Rows[i].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 255);
                            else
                                pvtSecondary.Rows[i].DefaultCellStyle.BackColor = Color.FromArgb(231, 239, 255);
                        }
                    }
                }
            }
        }

        #region Unused method EnableControlsBasedOnStatus
        ///// <summary>
        ///// Enables or disables controls based on status
        ///// </summary>
        //private void EnableControlsBasedOnStatus()
        //{
        //    try
        //    {
        //        #region INV001 - Enabling the form fields based on Status field

        //        object currentUserEmployeePOS = Globals.SqlIndex(EmployeeTableName, REStorePOSIdFieldName, this.SystemClient.UserProfile.EmployeeId);
        //        DataTable cashier = Globals.GetDataTable(CashierLoginsForTodaywithPOSQueryName, new object[] { currentUserEmployeePOS }, new string[] { StaffIdFieldName });
        //        object cashierStaffId = DBNull.Value;
        //        if((cashier != null) && (cashier.Rows.Count > 0))
        //            cashierStaffId = cashier.Rows[0][StaffIdFieldName];                    
        //        //else
        //        //{
        //            //if (this.RecordId == null)
        //            //{
        //            //    this.FormView.CloseForm(true);
        //            //    if (PivotalMessageBox.Show("No Cashier found logged in to the POS.", MessageBoxButtons.OK, MessageBoxIcon.Warning) == DialogResult.OK)
        //            //        Globals.NewForm("RE_Cashier_Log", null);
        //            //}
        //        //}

        //        if (this.FormView.FormName == REGoodsIssueClientForm)
        //        {
        //            //if (this.RecordId == null)
        //            //{
        //            //    this.PrimaryDataRow[FromStaffIdFieldName] = cashierStaffId;
        //            //    this.FormView.Dirty = false;
        //            //}
        //            //else
        //            //{
        //            //    if (this.PrimaryDataRow[FromStaffIdFieldName] == DBNull.Value)
        //            //    {
        //            //        this.PrimaryDataRow[FromStaffIdFieldName] = cashierStaffId;
        //            //        this.FormView.Dirty = false;
        //            //    }
        //            //}
        //            ////If status is not New or Hold show the form as readonly - Note:- buttons will be enabled in the next region
        //            //if (TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]) != Status.New &&
        //            //    TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]) != Status.Hold)
        //            //    this.EnableDisableAllFields(false);
        //        }
        //        else if (this.FormView.FormName == REGoodsReceiveClientForm)
        //        {
        //            #region INV012
        //            if (this.RecordId == null)
        //            {
        //                this.PrimaryDataRow[ToStaffIdFieldName] = cashierStaffId;
        //                this.FormView.Dirty = false;
        //            }
        //            else
        //            {
        //                if (this.PrimaryDataRow[ToStaffIdFieldName] == DBNull.Value)
        //                {
        //                    this.PrimaryDataRow[ToStaffIdFieldName] = cashierStaffId;
        //                    this.FormView.Dirty = false;
        //                }
        //                if (this.PrimaryDataRow[ReceiveDateFieldName] == DBNull.Value)
        //                {
        //                    this.PrimaryDataRow[ReceiveDateFieldName] = DateTime.Now;
        //                    this.FormView.Dirty = false;
        //                }
        //            }
        //            if (TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]) == Status.Issued)
        //            {
        //                this.PrimaryDataRow[Status.FieldName] = Status.Pending;
        //                this.FormControl.GetControlByDataName(Status.FieldName).Enabled = false;
        //            }
        //            else if (TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]) == Status.Pending)
        //                this.FormControl.GetControlByDataName(Status.FieldName).Enabled = false;
        //            else if (TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]) == Status.Received)
        //            {
        //                this.EnableDisableAllFields(false);
        //                if (TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]) == Status.Received)
        //                {
        //                    PivotalButton linkPvtlBtn = this.FormControl.GetControlByName("PivotalButton1") as PivotalButton;
        //                    if (linkPvtlBtn != null)
        //                        linkPvtlBtn.Enabled = false;
        //                }                        
        //            }
        //            else
        //                this.EnableDisableAllFields(false);

        //            #endregion
        //        }
        //        else if (this.FormView.FormName == RENewGoodsReceiveTemp)
        //        {
        //            this.PrimaryDataRow[ToStaffIdFieldName] = cashierStaffId;
        //        }
        //        #endregion

        //        //Enable /Disable Buttons on Issue form based on "Status" field value.
        //        this.EnableDisableButtons();
        //    }
        //    catch (Exception exc)
        //    {
        //        Globals.HandleException(exc, true);
        //    }
        //}
        #endregion

        /// <summary>
        /// Method to check if the logged in user is Cashier or Not
        /// </summary>
        /// <history>
        /// Revision#      Date            Author          Description
        ///                07/Mar/2012     HD              
        /// </history>
        private object IsCashierLogin()
        {
            object cashierStaffId = DBNull.Value;
            try
            {
                object currentUserEmployeePOS = Globals.SqlIndex(EmployeeTableName, REStorePOSIdFieldName, this.SystemClient.UserProfile.EmployeeId);
                DataTable cashier = Globals.GetDataTable(CashierLoginsForTodaywithPOSQueryName, new object[] { currentUserEmployeePOS }, new string[] { StaffIdFieldName });
                if ((cashier != null) && (cashier.Rows.Count > 0))
                    cashierStaffId = cashier.Rows[0][StaffIdFieldName];
            }            
            catch (Exception exc)
            {
                Globals.HandleException(exc, true);                
            }
            return cashierStaffId;
        }
        
        public void EnableDisableButtons()
        {
            try
            {
                #region Enable /Disable Buttons on Issue form based on "Status" field value.

                if (this.FormView.FormName == REGoodsIssueClientForm)
                {
                    PivotalButton createNewGIPvtlBtn = this.FormControl.GetControlByName(CreateNewGIButton) as PivotalButton;
                    PivotalButton removeItemsPvtlBtn = this.FormControl.GetControlByName(RemoveItemsButton) as PivotalButton;
                    PivotalButton createCopyPvtlBtn = this.FormControl.GetControlByName(CreateCopyButton) as PivotalButton;
                    //PivotalButton printGoodsPvtlBtn = this.FormControl.GetControlByName(PrintGoodsIssueButton) as PivotalButton;

                    bool enableCreateNewGIBtn = false;
                    bool enableRemoveItemsBtn = false;
                    bool enableCreateCopyBtn = false;
                    //bool enablePrintGoodsIssue = false;
                    if (TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]) == Status.Issued)
                    {
                        //Enable PrintGoods & CreateCopy
                        enableCreateCopyBtn = true;
                        //enablePrintGoodsIssue = true;
                        this.FormControl.GetControlByDataName(Status.FieldName).Enabled = true;
                    }
                    if (TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]) == Status.Cancel)
                    {
                        //Enable only CreateCopy
                        enableCreateCopyBtn = true;
                    }
                    if (TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]) == Status.Pending)
                    {
                        //Enable Remove Items & Create GI
                        enableRemoveItemsBtn = true;
                        enableCreateNewGIBtn = true;
                    }
                    if (TypeConvert.ToString(this.PrimaryDataRow[Status.FieldName]) == Status.Received)
                    {
                        //Enable only CreateCopy
                        enableCreateCopyBtn = true;
                    }
                    //if (printGoodsPvtlBtn != null)
                    //    printGoodsPvtlBtn.Enabled = enablePrintGoodsIssue;
                    if (createNewGIPvtlBtn != null)
                        createNewGIPvtlBtn.Enabled = enableCreateNewGIBtn;
                    if (removeItemsPvtlBtn != null)
                        removeItemsPvtlBtn.Enabled = enableRemoveItemsBtn;
                    if (createCopyPvtlBtn != null)
                        createCopyPvtlBtn.Enabled = enableCreateCopyBtn;
                }
                #endregion
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc, true);
            }
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="enableFields"></param>
        public void EnableDisableAllFields(bool enableFields)
        {
            try
            {
                IFormView formView = (IFormView)ClientContext.ClientAPIService.GetActiveContentObject();
                PivotalClientFormControl formControl = (PivotalClientFormControl)formView.FormControl;

                // ### Enable/Disable all fields in Primary Segment
                // For each Column/Field in the Primary Segment on the Form
                for (int i = 0; i < formView.FormData.DataTemplate.PrimaryDataSection.DataSectionColumns.Count; i++)
                {
                    try
                    {
                        // Enable/Disable the field on the Primary Segment
                        // If the Field is not on the Primary Segment/Data Template for some odd reason, then the
                        // exception will be caught & we'll continue with the rest of the for() loop.
                        formControl.GetControlByDataName(formView.FormData.DataTemplate.PrimaryDataSection.DataSectionColumns[i].Name).Enabled = enableFields;
                    }
                    catch (System.NullReferenceException exc)
                    {
                        // If the System.NullReferenceException exception has been raised, it means that the 
                        // Field does not actually exist on the Form.  Therefore, ignore it, and continue the 
                        // foreach() loop
                    }
                    catch (Exception exc)
                    {
                        // throw any other type of exception
                        Globals.HandleException(exc, true);
                    }
                }

                // ### Enable/Disable all fields in Secondary Segments
                // For each Secondary Segment on the form...
                for (int i = 0; i < formView.FormData.DataTemplate.SecondaryDataSections.Count; i++)
                {
                    // Get the Secondary Segment into a PivotalSecondary object...
                    PivotalSecondary secondary = formControl.GetSecondary(formView.FormData.DataTemplate.SecondaryDataSections[i].Name);
                    //NK commeted the secondary.Enabled = false; to allow for scrolling of the secondary.
                    
                    //secondary.Enabled = false;
                    // For each column in that Secondary...
                    for (int j = 0; j < secondary.Columns.Count; j++)
                    {
                        try
                        {
                            // ...either enable it (ReadOnly = False) or disable it (ReadOnly = true)
                            secondary.Columns[j].ReadOnly = !(enableFields);
                        }
                        catch (System.NullReferenceException exc)
                        {
                            // If the System.NullReferenceException exception has been raised, it means that the 
                            // Field does not actually exist on the Secondary.  Therefore, ignore it, and continue the 
                            // foreach() loop
                        }
                        catch (Exception exc)
                        {
                            // throw any other type of exception
                            Globals.HandleException(exc, true);
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc, true);
            }
        }

        /// <summary>
        /// Check if reducing the product quantity by the quantity will make the inventory level negative. If so inform the user about the same.
        /// </summary>
        /// <param name="productSKUId">Product SKU selected in the grid</param>
        /// <param name="storageLocationId">Primary storage location for this store</param>
        /// <param name="quantity">Quantity to be used</param>
        private bool ValidateInventory(object productSKUId, object storageLocationId)
        {
            try
            {
                bool createInventoryProduct = true;
                //Fetch available quantity.
                DataTable stockAvailable = Globals.GetDataTable("RE_Inventory for SKU? Storage Location?", new object[] { productSKUId, storageLocationId },
                    "Quantity_Actual");
                if (stockAvailable != null && stockAvailable.Rows.Count > 0)
                {
                    int totalQty = this.DataSet.Tables[InventoryTransferProductSegment].AsEnumerable().Where(a => Id.Create(a["Product_SKU_Id"])
                        == Id.Create(productSKUId)).Sum(a => TypeConvert.ToInt32(a["Quantity_Issued"]));

                    if (TypeConvert.ToInt32(stockAvailable.Rows[0]["Quantity_Actual"]) < totalQty + 1)
                    {
                        if (PivotalMessageBox.Show("Deducting the specified quantity from the current inventory level will make it -ve.", MessageBoxButtons.OKCancel,
                            MessageBoxIcon.Information) == DialogResult.OK)
                            createInventoryProduct = true;
                        else
                        {
                            this.PrimaryDataRow[ProductBarcodeFieldName] = DBNull.Value;
                            this.PrimaryDataRow[ProductSKUIdFieldName] = DBNull.Value;
                            this.PrimaryDataRow[ProductIdFieldName] = DBNull.Value;
                            ((PivotalForeignKey)this.FormControl.GetControlByDataName(ProductSKUIdFieldName)).ReadOnly = true;
                            createInventoryProduct = false;
                        }
                    }
                }
                else
                {
                    if (PivotalMessageBox.Show(this.DefaultResourceBundle.GetString(InventoryNotFound), MessageBoxButtons.OKCancel,
                            MessageBoxIcon.Information) == DialogResult.OK)
                        createInventoryProduct = true;
                    else
                    {
                        this.PrimaryDataRow[ProductBarcodeFieldName] = DBNull.Value;
                        this.PrimaryDataRow[ProductSKUIdFieldName] = DBNull.Value;
                        this.PrimaryDataRow[ProductIdFieldName] = DBNull.Value;
                        ((PivotalForeignKey)this.FormControl.GetControlByDataName(ProductSKUIdFieldName)).ReadOnly = true;
                        createInventoryProduct = false;
                    }
                }
                return createInventoryProduct;
            }
            catch (Exception exc)
            {
                return Globals.HandleException(exc, true);
            }
        }

        /// <summary>
        /// Update the GI,GR and Open Qty in case of received is checked/unchecked.
        /// </summary>
        /// <param name="transferProductRow"> Item row for which the checkbox is checked/unchecked</param>
        /// <param name="receivedCheck">Whether the checkbox is checked/unchecked</param>
        private void ReceivedCheck(DataRow transferProductRow, bool receivedCheck)
        {
            if (!TypeConvert.ToBoolean(transferProductRow["GR_NewTransfer"]))
            {
                if (receivedCheck)
                {
                    if (TypeConvert.ToInt16(transferProductRow[QuantityOpenFieldName]) != 0)
                    {
                        //transferProductRow[QuantityOpenFieldName] = Convert.ToInt32(transferProductRow[QuantityOpenFieldName]) + 1;
                        //transferProductRow[QuantityReceivedFieldName] = TypeConvert.ToInt16(transferProductRow[QuantityReceivedFieldName]) + 1;
                        //this.PrimaryDataRow["Received_Quantity"] = TypeConvert.ToInt32(this.PrimaryDataRow["Received_Quantity"]) + 1;
                        //if (TypeConvert.ToInt16(transferProductRow[QuantityOpenFieldName]) == 0)
                        //    transferProductRow[ReceivedFieldName] = true;

                        //As the value of GI can be >1 when it comes from SAP.
                        //this.PrimaryDataRow["Received_Quantity"] = TypeConvert.ToInt16(this.PrimaryDataRow["Received_Quantity"]) +
                        //        Math.Abs(TypeConvert.ToInt16(transferProductRow[QuantityOpenFieldName]));
                        //transferProductRow[QuantityReceivedFieldName] = TypeConvert.ToInt16(transferProductRow[QuantityReceivedFieldName]) +
                        //    Math.Abs(TypeConvert.ToInt16(transferProductRow[QuantityOpenFieldName]));
                        transferProductRow[QuantityOpenFieldName] = 0;
                        transferProductRow[ReceivedFieldName] = true;
                    }
                    else
                        if(!TypeConvert.ToBoolean(transferProductRow[ReceivedFieldName]))
                            transferProductRow[ReceivedFieldName] = true;
                }
                else
                {
                    //transferProductRow[QuantityOpenFieldName] = Convert.ToInt32(transferProductRow[QuantityOpenFieldName]) - 1;
                    //transferProductRow[QuantityReceivedFieldName] = TypeConvert.ToInt16(transferProductRow[QuantityReceivedFieldName]) - 1;
                    //this.PrimaryDataRow["Received_Quantity"] = TypeConvert.ToInt32(this.PrimaryDataRow["Received_Quantity"]) - 1;
                    //if (TypeConvert.ToInt16(transferProductRow[QuantityOpenFieldName]) != 0)
                    //    transferProductRow[ReceivedFieldName] = false;

                    //As the value of GI can be >1 when it comes from SAP.
                    transferProductRow[QuantityOpenFieldName] = -TypeConvert.ToInt16(transferProductRow[QuantityIssuedFieldName]);
                    //this.PrimaryDataRow["Received_Quantity"] = TypeConvert.ToInt16(this.PrimaryDataRow["Received_Quantity"]) -
                    //    TypeConvert.ToInt16(transferProductRow[QuantityReceivedFieldName]);
                    //transferProductRow[QuantityReceivedFieldName] = 0;   
                    transferProductRow[ReceivedFieldName] = false;
                }
            }
        }

        /// <summary>
        /// Fetch Product SKU's
        /// </summary>
        /// <param name="productSerialNumber"></param>
        /// //Modified by Deb
        private void AddProductToGrid(DataTable product, DataTable productSerialNumber,DataTable invTransferProducts,bool serialized)
        {
            try
            {
                DataTable orderProducts = this.FormData.DataSet.Tables["RE_Inv_Transfer_Product_RE_Inv"];
                DataTable invTransferRecBatchProducts = this.FormData.DataSet.Tables["RE_Inv_Trnsf_Rec_Batch_Invento"];
                //IEnumerable<DataRow> row = this.FormData.DataSet.Tables["RE_Inv_Transfer_Product_RE_Inv"].AsEnumerable();
                if (productSerialNumber != null)
                {
                    //For serialized items, do not allow addition of an item which is present in the grid with same serial number and same product id.
                    if (orderProducts.AsEnumerable().Count(a => Id.Equals(Id.Create(a["RE_Product_Serial_No_Id"]),
                        Id.Create(productSerialNumber.Rows[0]["RE_Product_Serial_No_Id"]))
                        && Id.Equals(Id.Create(a["Product_Id"]), Id.Create(this.PrimaryDataRow["Product_Id"]))) > 0)
                    {
                        if (this.FormView.FormName == "RE_Goods_Receive" || this.FormView.FormName == "RE_RMA")
                        {
                            PivotalMessageBox.Show("Item has been fully received.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            PivotalMessageBox.Show("Item has been already added", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        return;
                    }
                }
                string message = string.Empty;
                if (this.FormView.FormName == "RE_RMA")
                {
                    DataTable transferProducts = this.FormData.DataSet.Tables[InventoryTransferProductSegment];
                    base.NewSecondaryRecord(InventoryTransferProductSegment);
                    DataRow transferProduct = transferProducts.Rows[transferProducts.Rows.Count - 1];
                    if ((product != null && product.Rows.Count > 0) && (productSerialNumber == null))
                    {
                        transferProduct[ProductIdFieldName] = product.Rows[0][ProductIdFieldName];
                    }
                    else
                    {
                        transferProduct[ProductIdFieldName] = productSerialNumber.Rows[0][ProductIdFieldName];
                    }
                    if (productSerialNumber != null && productSerialNumber.Rows.Count > 0)
                    {
                        transferProduct["RE_Product_Serial_No_Id"] = productSerialNumber.Rows[0]["RE_Product_Serial_No_Id"];
                    }
                    else
                    {
                        transferProduct["RE_Product_Serial_No_Id"] = DBNull.Value;
                    }
                    transferProduct["Quantity_Issued"] = 1;
                }
                else if (this.FormView.FormName == "RE_Goods_Issue")
                {
                    DataTable transferProducts = this.FormData.DataSet.Tables[InventoryTransferProductSegment];
                    base.NewSecondaryRecord(InventoryTransferProductSegment);
                    DataRow transferProduct = transferProducts.Rows[transferProducts.Rows.Count - 1];
                    if ((product != null && product.Rows.Count > 0) && (productSerialNumber == null))
                    {
                        transferProduct[ProductIdFieldName] = product.Rows[0][ProductIdFieldName];
                    }
                    else
                    {
                        transferProduct[ProductIdFieldName] = productSerialNumber.Rows[0][ProductIdFieldName];
                    }
                    transferProduct[QuantityIssuedFieldName] = 1;
                    transferProduct[QuantityReceivedFieldName] = 0;
                    transferProduct[QuantityOpenFieldName] = -1;
                    transferProduct[ReceivedFieldName] = false;
                    if (productSerialNumber != null && productSerialNumber.Rows.Count > 0)
                    {
                        transferProduct["RE_Product_Serial_No_Id"] = productSerialNumber.Rows[0]["RE_Product_Serial_No_Id"];
                    }
                }
                else if (this.FormView.FormName == "RE_Goods_Receive")
                {
                    DataTable transferRecBatchProducts = this.FormData.DataSet.Tables["RE_Inv_Trnsf_Rec_Batch_Invento"];
                    base.NewSecondaryRecord("RE_Inv_Trnsf_Rec_Batch_Invento");
                    DataRow transferProduct = transferRecBatchProducts.Rows[transferRecBatchProducts.Rows.Count - 1];
                    transferProduct["Receive_Batch_ID"] = this.PrimaryDataRow["Receive_Batch_ID"];
                    transferProduct["Receive_Batch_Date"] = DateTime.Now;
                    transferProduct["External_System_Updated"] = false;
                    if (Convert.IsDBNull(this.PrimaryDataRow["Product_Id"]))
                    {
                        transferProduct["Product_Id"] = product.Rows[0][ProductIdFieldName];
                    }
                    else
                    {
                        transferProduct["Product_Id"] = this.PrimaryDataRow["Product_Id"];
                    }
                    if(!Convert.IsDBNull(this.PrimaryDataRow["RE_Serial_Number"]))
                    {
                        DataTable serialNumberId = Globals.GetDataTable("RE_ProductSerialNo based on Serial_Number?Product?", new object[] { this.PrimaryDataRow["RE_Serial_Number"],
                        this.PrimaryDataRow["Product_Id"]},
                            new string[] { "RE_Product_Serial_No_Id" });
                        if (serialNumberId != null && serialNumberId.Rows.Count == 1)
                        {
                            transferProduct["Product_Serial_No_Id"] = serialNumberId.Rows[0]["RE_Product_Serial_No_Id"];
                        }
                        else
                        {
                            transferProduct["Product_Serial_No_Id"] = this.PrimaryDataRow["RE_Product_Serial_No_Id"];
                        }
                    }
                    
                    if (!Convert.IsDBNull(this.PrimaryDataRow["RE_Product_Serial_No_Id"]))
                    {
                        string serialNumber = TypeConvert.ToString(Globals.SqlIndex("RE_Product_Serial_No", "Serial_Number", Id.Create(this.PrimaryDataRow["RE_Product_Serial_No_Id"])));
                        transferProduct["Serial_Number"] = serialNumber.ToUpper();
                        transferProduct["Product_Serial_No_Id"] = this.PrimaryDataRow["RE_Product_Serial_No_Id"];
                    }
                    else
                    {
                        transferProduct["Serial_Number"] = TypeConvert.ToString(this.PrimaryDataRow["RE_Serial_Number"]).ToUpper();
                    }

                    if (serialized)
                    {
                        IEnumerable<DataRow> row=null;
                        if (Convert.IsDBNull(this.PrimaryDataRow["RE_Product_Serial_No_Id"]) && !Convert.IsDBNull(this.PrimaryDataRow["RE_Serial_Number"]))
                        {
                            DataTable serialNumberId = Globals.GetDataTable("RE_ProductSerialNo based on Serial_Number?Product?", new object[] { this.PrimaryDataRow["RE_Serial_Number"],
                            this.PrimaryDataRow["Product_Id"]}
                                    , new string[] { "RE_Product_Serial_No_Id" });
                            if (serialNumberId != null && serialNumberId.Rows.Count == 1)
                            {
                                row = this.FormData.DataSet.Tables["RE_Inv_Transfer_Product_RE_Inv"].AsEnumerable().
                                    Where(a => Id.Create(a["Product_Id"]) == Id.Create(this.PrimaryDataRow["Product_Id"])
                                                                 && Id.Create(a["RE_Product_Serial_No_Id"]) == Id.Create(serialNumberId.Rows[0]["RE_Product_Serial_No_Id"])
                                                                 && TypeConvert.ToBoolean(a["Received"]) == false);
                            }
                            else
                            {
                                row = this.FormData.DataSet.Tables["RE_Inv_Transfer_Product_RE_Inv"].AsEnumerable().
                                    Where(a => Id.Create(a["Product_Id"]) == Id.Create(this.PrimaryDataRow["Product_Id"])
                                                                 && Id.Create(a["RE_Product_Serial_No_Id"]) == Id.Create(this.PrimaryDataRow["RE_Product_Serial_No_Id"])
                                                                 && TypeConvert.ToBoolean(a["Received"]) == false);
                            }
                        }
                        else
                        {
                            row = this.FormData.DataSet.Tables["RE_Inv_Transfer_Product_RE_Inv"].AsEnumerable().
                                    Where(a => Id.Create(a["Product_Id"]) == Id.Create(this.PrimaryDataRow["Product_Id"])
                                                                 && Id.Create(a["RE_Product_Serial_No_Id"]) == Id.Create(this.PrimaryDataRow["RE_Product_Serial_No_Id"])
                                                                 && TypeConvert.ToBoolean(a["Received"]) == false);
                        }
                        if (row != null && row.Count() == 1)
                        {
                            if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "PO Receive"))
                            {
                                transferProduct["External_Line_Item_No"] = row.First()["RE_Ext_PO_Line_Item_No"];
                            }
                            else if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "Inventory Receive"))
                            {
                                transferProduct["External_Line_Item_No"] = row.First()["RE_Ext_DO_Line_Item_No"];
                            }
                        }
                        else
                        {
                            row = this.FormData.DataSet.Tables["RE_Inv_Transfer_Product_RE_Inv"].AsEnumerable().
                                Where(a => Id.Create(a["Product_Id"]) == Id.Create(this.PrimaryDataRow["Product_Id"])
                                                             && Id.Create(a["RE_Product_Serial_No_Id"]) == null
                                                             && TypeConvert.ToBoolean(a["Received"]) == false);
                            if (row != null && row.Count() == 1)
                            {
                                if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "PO Receive"))
                                {
                                    transferProduct["External_Line_Item_No"] = row.First()["RE_Ext_PO_Line_Item_No"];
                                }
                                else if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "Inventory Receive"))
                                {
                                    transferProduct["External_Line_Item_No"] = row.First()["RE_Ext_DO_Line_Item_No"];
                                }
                            }
                        }
                    }
                    else
                    {
                        IEnumerable<DataRow> row = null;
                        if (Convert.IsDBNull(this.PrimaryDataRow["Product_Id"]))
                        {
                            row = this.FormData.DataSet.Tables["RE_Inv_Transfer_Product_RE_Inv"].AsEnumerable().
                                Where(a => Id.Create(a["Product_Id"]) == Id.Create(product.Rows[0]["Product_Id"])
                                                             && TypeConvert.ToBoolean(a["Received"]) == false);
                        }
                        else
                        {
                            row = this.FormData.DataSet.Tables["RE_Inv_Transfer_Product_RE_Inv"].AsEnumerable().
                                  Where(a => Id.Create(a["Product_Id"]) == Id.Create(this.PrimaryDataRow["Product_Id"])
                                                        && TypeConvert.ToBoolean(a["Received"]) == false);
                        }
                        if (row != null && row.Count() >0 )
                        {
                            if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "PO Receive"))
                            {
                                transferProduct["External_Line_Item_No"] = row.First()["RE_Ext_PO_Line_Item_No"];
                            }
                            else if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "Inventory Receive"))
                            {
                                transferProduct["External_Line_Item_No"] = row.First()["RE_Ext_DO_Line_Item_No"];
                            }
                        }
                    }
                    transferProduct["Qty"] = 1;
                    if (String.Equals(TypeConvert.ToString(this.PrimaryDataRow["Transfer_Type"]), "Inventory Transfer"))
                    {
                        IEnumerable<DataRow> row = null;
                        //if (Convert.IsDBNull(this.PrimaryDataRow["Product_Id"]))
                        //{
                        //    row = this.FormData.DataSet.Tables["RE_Inv_Transfer_Product_RE_Inv"].AsEnumerable().
                        //            Where(a => Id.Create(a["Product_Id"]) == Id.Create(product.Rows[0]["Product_Id"])
                        //                                         && TypeConvert.ToBoolean(a["Received"]) == false);
                        //}
                        //else
                        //{
                        if (serialized)
                        {
                            if (Convert.IsDBNull(this.PrimaryDataRow["RE_Product_Serial_No_Id"]) && !Convert.IsDBNull(this.PrimaryDataRow["RE_Serial_Number"]))
                            {
                                DataTable serialNumberId = Globals.GetDataTable("RE_ProductSerialNo based on Serial_Number?Product?", new object[] { this.PrimaryDataRow["RE_Serial_Number"],
                                this.PrimaryDataRow["Product_Id"]}
                                    , new string[] { "RE_Product_Serial_No_Id" });
                                if (serialNumberId != null && serialNumberId.Rows.Count == 1)
                                {
                                    row = this.FormData.DataSet.Tables["RE_Inv_Transfer_Product_RE_Inv"].AsEnumerable().
                                   Where(a => Id.Create(a["Product_Id"]) == Id.Create(this.PrimaryDataRow["Product_Id"])
                                                                && Id.Create(a["RE_Product_Serial_No_Id"]) == Id.Create(serialNumberId.Rows[0]["RE_Product_Serial_No_Id"])
                                                                && TypeConvert.ToBoolean(a["Received"]) == false);
                                }
                                //else
                                //{
                                //    row = this.FormData.DataSet.Tables["RE_Inv_Transfer_Product_RE_Inv"].AsEnumerable().
                                //        Where(a => Id.Create(a["Product_Id"]) == Id.Create(this.PrimaryDataRow["Product_Id"])
                                //                                     && Id.Create(a["RE_Product_Serial_No_Id"]) == Id.Create(this.PrimaryDataRow["RE_Product_Serial_No_Id"])
                                //                                     && TypeConvert.ToBoolean(a["Received"]) == false);
                                //}
                            }
                            else
                            {
                                row = this.FormData.DataSet.Tables["RE_Inv_Transfer_Product_RE_Inv"].AsEnumerable().
                                        Where(a => Id.Create(a["Product_Id"]) == Id.Create(this.PrimaryDataRow["Product_Id"])
                                                                     && Id.Create(a["RE_Product_Serial_No_Id"]) == Id.Create(this.PrimaryDataRow["RE_Product_Serial_No_Id"])
                                                                     && TypeConvert.ToBoolean(a["Received"]) == false);
                            }
                        }
                        else
                        {
                            //DS: 05062013 - Check condition was for null check of Product_Id which was never setting the Issue_Line_Number field.
                            if (!Convert.IsDBNull(this.PrimaryDataRow["Product_Id"]))
                            {
                                row = this.FormData.DataSet.Tables["RE_Inv_Transfer_Product_RE_Inv"].AsEnumerable().
                                        Where(a => Id.Create(a["Product_Id"]) == Id.Create(product.Rows[0]["Product_Id"])
                                                                     && TypeConvert.ToBoolean(a["Received"]) == false);
                            }
                            //AS:18102013 -  Check condition was for null check of Product_Id which was never setting the Issue_Line_Number field.
                            else if (!Convert.IsDBNull(product.Rows[0]["Product_Id"]))
                            {
                                row = this.FormData.DataSet.Tables["RE_Inv_Transfer_Product_RE_Inv"].AsEnumerable().
                                       Where(a => Id.Create(a["Product_Id"]) == Id.Create(product.Rows[0]["Product_Id"])
                                                                    && TypeConvert.ToBoolean(a["Received"]) == false);
                            }
                        }
                        if (row != null && row.Count() >0 )
                        {
                            transferProduct["Issue_Line_Number"] = row.First()["Serial_Number"];
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc, true);
            }
        }

        /// <summary>
        /// Check for availability of the inventory. If not warn the user.
        /// </summary>
        /// <param name="quantity">Quantity to be verified.</param>
        /// <param name="isFromQty"></param>
        /// <returns>True if available otherwise false.</returns>
        /// <summary>
        private bool InventoryCheck(int quantity, bool isFromQty, object productId, DataRow orderProduct)
        {
            bool available = false;
            oldQty = previousQuantity;
            //Check for Inventory. No Inventory, do not allow to add products. 
            DataTable stockAvailable = Globals.GetDataTable("RE_Inventory for Product? At current Store",
                new object[] { productId }, "Quantity_Actual");

            if (stockAvailable != null && stockAvailable.Rows.Count > 0 && TypeConvert.ToInt16(stockAvailable.Rows[0]["Quantity_Actual"]) >= 1)
            {
                int totalQty = this.DataSet.Tables["RE_Inv_Transfer_Product_RE_Inv"].AsEnumerable().Where(a => (Id.Create(a["Product_Id"])
                     == Id.Create(productId) && TypeConvert.ToInt32(a["Quantity_Issued"]) > 0)).Sum(a => TypeConvert.ToInt32(a["Quantity_Issued"]));

                if (!isFromQty)
                    totalQty = totalQty + 1;

                if (quantity > 0 && TypeConvert.ToInt32(stockAvailable.Rows[0]["Quantity_Actual"]) < totalQty)
                {
                    if (isFromQty)
                        popupShown = true;
                    PivotalMessageBox.Show("No more stock for the Product.", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    available = false;
                    popupShown = false;
                }
                else
                    available = true;
            }
            else
                PivotalMessageBox.Show("No stock found for the Product.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            return available;
        }

        #endregion
    }
}
